package net.cmkj.mine.core.admin.service;

import com.jfinal.aop.Inject;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import net.cmkj.mine.bean.Columns;
import net.cmkj.mine.bean.Mine;
import net.cmkj.mine.bean.Modules;
import net.cmkj.mine.bean.SysUser;
import net.cmkj.mine.common.model.DataGridModel;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.util.*;
import net.sf.json.JSONObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

public class MineService {

    private static Logger log = LogManager.getLogger(MineService.class);

    @Inject
    private Mine dao;

    private String table = PropKit.use("table.txt").get("table");

    /**
     * 获取列表（分页）
     * @param pageNumber
     * @param pageSize
     * @param page
     * @param request
     * @param orderStr
     * @return
     * @throws Exception
     */
    public DataGridModel getList(int pageNumber, int pageSize, String page, HttpServletRequest request, String orderStr) throws Exception {
        log.info("获取列表（分页）");
        Modules module = Modules.dao.getModuleByUrl(page, table);
        Page<Record> pageInfo = dao.getList(pageNumber, pageSize, module.getId(), table+module.getStr("tablename"), getQueryArguments(module, request), orderStr);
        DataGridModel result = DataGridModelUtils.toDataGridView(pageInfo);
        return result;
    }

    /**
     * 获取列表
     * @param page
     * @param request
     * @param orderStr
     * @return
     * @throws Exception
     */
    public DataGridModel getList(String page, HttpServletRequest request, String orderStr) throws Exception {
        log.info("获取列表");
        Modules module = Modules.dao.getModuleByUrl(page, table);
        DataGridModel result = new DataGridModel();
        List<Record> list = dao.getList(module.getId(), table+module.getStr("tablename"), getQueryArguments(module, request), orderStr);
        result.setCount(list.size());
        result.setData(list);
        return result;
    }

    /**
     * 获取字段列表
     * @param moduleid
     * @return
     * @throws Exception
     */
    public List<Columns> showColumns(long moduleid) throws Exception {
        log.info("获取字段列表");
        return Columns.dao.getShowList(moduleid);
    }
    /**
     * 获取字段列表
     * @param moduleid
     * @return
     * @throws Exception
     */
    public List<Columns> inportColumns(long moduleid) throws Exception {
        log.info("获取字段列表");
        return Columns.dao.getInportList(moduleid);
    }

    /**
     * 获取查询字段
     * @param module
     * @return
     * @throws Exception
     */
    public List<Columns> getSearchedList(Modules module) throws Exception {
        log.info("获取查询字段");
        return dao.getSearchedList(module.getId(), module.getSearchCids());
    }

    /**
     * 获取对象
     * @param tablename
     * @param id
     * @return
     * @throws Exception
     */
    public Map<String, Object> findById(String tablename, long id) throws Exception {
        log.info("获取对象");
        return dao.findById(tablename, id).getColumns();
    }

    /**
     * 获取下拉选择框
     * @param moduleid
     * @return
     * @throws Exception
     */
    public List<Record> getSelectData(long moduleid, String foreignKey) throws Exception {
        Modules module  = Modules.dao.findById(moduleid);
        //Columns column = Columns.dao.findByPosition(moduleid, 2);
        return dao.getSelectData(table+module.getTablename(), foreignKey);
    }

    /**
     * 对象保存
     * @param tablename
     * @param params
     * @return
     * @throws Exception
     */
    public InvokeResult save(String tablename, Map<String, String[]> params, SysUser user) throws Exception {
        log.info("对象保存");
        Record record = new Record();
        for (Entry<String, String[]> entry : params.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            if (!"tablename".equalsIgnoreCase(key) && !"moduleid".equalsIgnoreCase(key)&& !"file".equalsIgnoreCase(key)) {
                if ("id".equalsIgnoreCase(key)) {
                    if (StrKit.notBlank(values[0])) {
                        record.set(key, CommonUtils.converLong(values[0]));
                    }
                } else {
                    String value = values[0];
                    if(value==""||value.equals("")){
                        value = null;
                    }
                    record.set(key, value);
                }
            }
        }
        return dao.save(tablename, record,user);
    }

    /**
     * 对象删除
     * @param tablename
     * @param ids
     * @return
     * @throws Exception
     */
    public InvokeResult delete(String tablename, String ids) throws Exception{
        log.info("对象删除");
        return dao.deleteByIds(tablename, ids);
    }
    /**
     * 对象附件删除
     * @param tablename
     * @param ids
     * @return
     * @throws Exception
     */
    public InvokeResult deleteFile(String tablename, String ids) throws Exception{
        log.info("对象删除");
        return dao.deleteFlieByIds(tablename, ids);
    }

    /**
     * 获取附件列表
     * @param tablename
     * @param parentid
     * @return
     * @throws Exception
     */
    public DataGridModel getAttachList(String tablename, long parentid) throws Exception {
        log.info("获取附件列表");
        List<Record> list = dao.getAttachList(tablename, parentid);
        DataGridModel result = new DataGridModel();
        result.setCount(list.size());
        result.setData(list);
        return result;
    }

    /**
     * 获取附件
     * @param tablename
     * @param id
     * @return
     * @throws Exception
     */
    public Record getAttach(String tablename, long id) throws Exception {
        log.info("获取附件");
        return dao.getAttach(tablename, id);
    }

    /**
     * 添加附件
     * @param tablename
     * @param name
     * @param realname
     * @param parentid
     * @return
     * @throws Exception
     */
    public InvokeResult attachSave(String tablename, String name, String realname, long parentid) throws Exception {
        log.info("添加附件");
        Record record = new Record();
        record.set("name", name).set("realname", realname).set("parentid", parentid);
        if (Db.save(tablename+"_attach", record)) {
            return InvokeResult.success();
        } else {
            return InvokeResult.failure("添加附件失败！");
        }
    }

    public InvokeResult importExcel(long moduleid,int type, UploadFile up, SysUser user) throws Exception {
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                try {
                    Modules module = Modules.dao.findById(moduleid);
                    //List<Columns> columns = showColumns(moduleid);
                    List<Columns> columns = inportColumns(moduleid);
                    Columns columns1 = new Columns();
                    columns1.setColumnType("id");
                    columns1.setColumnName("id");
                    //添加Id字段
                    columns.add(0,columns1);
                    List<String[]> list = ExcelUtils.getData(up.getFile()).get(0);
                    if (list != null) {
                        for (int i = 0; i < list.size(); i++) {
                            Record record = new Record();
                            for (int j = 0; j < columns.size(); j++) {
                                Columns column = columns.get(j);
                                String columnType = column.getColumnType();
                                if (columnType.equals("file")){
                                    continue;
                                }else if (columnType.equals("yesorno")){
                                    if(list.get(i)[j].equals("否")){
                                        record.set(column.getColumnName(), 2);
                                    }else{
                                        record.set(column.getColumnName(), 1);
                                    }
                                }else if (columnType.equals("haveorno")){
                                    if(list.get(i)[j].equals("无")){
                                        record.set(column.getColumnName(), 2);
                                    }else{
                                        record.set(column.getColumnName(), 1);
                                    }
                                }else if (columnType.equals("sex")){
                                    if(list.get(i)[j].equals("女")){
                                        record.set(column.getColumnName(), 2);
                                    }else{
                                        record.set(column.getColumnName(), 1);
                                    }
                                }else if (columnType.equals("select")){
                                    if(column.getForeignTable()!=null){
                                        Modules modules = Modules.dao.findById(column.getForeignTable());
                                        List<Record> records = dao.getSelectData(table + modules.getTablename(), column.getForeignKey());
                                        for (int k = 0; k <records.size(); k++) {
                                            if(records.get(k).get("name").equals(list.get(i)[j])){
                                                record.set(column.getColumnName(),records.get(k).get("value"));
                                            }
                                        }
                                    }else{
                                        record.set(column.getColumnName(),"");
                                    }
                                }else{
                                    if (columnType.equals("id")){
                                        if (type == 0){
                                            //新增操作 不需要Id
                                            continue;
                                        }
                                    }

                                    if(StrKit.notBlank(list.get(i)[j])){
                                        record.set(column.getColumnName(),list.get(i)[j]);
                                    }
                                }
                                record.set("createuser",user.getId());
                                SimpleDateFormat format =new SimpleDateFormat("yy-MM-dd hh:mm:ss");
                                record.set("createdate",format.format(new Date()));
                            }
                            if (type == 0){
                                //新增操作
                                if (!Db.save(table+module.getTablename(), record)) {
                                    return false;
                                }
                            }else {
                                //覆盖操作
//                                if (!Db.update(table+module.getTablename(),record)){
//                                    return false;
//                                }
                                if (!dao.insertOrUpdate(table+module.getTablename(),record)){
                                    return false;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        });
        if (flag) {
            return InvokeResult.success();
        } else {
            return InvokeResult.failure("Excel导入失败！");
        }
    }

    /**
     * 导出列表
     * @param moduleid
     * @param tablename
     * @param type
     * @param orderStr
     * @param request
     * @param response
     * @throws Exception
     */
    public void exportExcel(long moduleid, String tablename, int type, String orderStr, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Columns> columns = showColumns(moduleid);
        Map<String, String> title = new LinkedHashMap<String, String>();
        title.put("id","id");
        for (Columns column : columns) {
            if(column.getColumnType().equals("file")){
                continue;
            }else{
                title.put(column.getColumnName(), column.getColumnComment());
            }
        }

        Modules module = Modules.dao.findById(moduleid);
        List<Record> list = new ArrayList<Record>();
        if (type == 1) {
            list = getExcelList(module, tablename, request, orderStr);
            for (int i = 0; i <list.size() ; i++) {
                Record record = list.get(i);
                for (Columns column : columns) {
                    String columnType = column.getColumnType();
                    String columnName = "";
                    if (columnType.equals("yesorno")){
                        columnName = column.getColumnName();
                        Integer yesorno = record.get(columnName);
                        if(yesorno==1){
                            record.set(columnName,"是");
                        }else if(yesorno==2){
                            record.set(columnName,"否");
                        }else{
                            record.set(columnName,"");
                        }
                    }else if (columnType.equals("haveorno")){
                        columnName = column.getColumnName();
                        Integer yesorno = record.get(columnName);
                        if(yesorno==1){
                            record.set(columnName,"有");
                        }else if(yesorno==2){
                            record.set(columnName,"无");
                        }else{
                            record.set(columnName,"");
                        }
                    }else if (columnType.equals("sex")){
                        columnName = column.getColumnName();
                        Integer yesorno = record.get(columnName);
                        if(yesorno==1){
                            record.set(columnName,"男");
                        }else if(yesorno==2){
                            record.set(columnName,"女");
                        }else{
                            record.set(columnName,"");
                        }
                    }else if (columnType.equals("file")){
                        columnName = column.getColumnName();
                        record.remove(columnName);
                    }
                }
            }
        }
        ExportExcel ep = new ExportExcel(module.getName()+"列表", title, list, response);
        ep.export();
    }

    /**
     * 获取导出列表
     * @param module
     * @param tablename
     * @param request
     * @param orderStr
     * @return
     * @throws Exception
     */
    public List<Record> getExcelList(Modules module, String tablename, HttpServletRequest request, String orderStr) throws Exception {
        log.info("获取导出列表");
        return dao.getList(module.getId(), tablename, getExportQueryArguments(module, request), orderStr);
    }

    /**
     * 获取查询条件
     * @param module
     * @param request
     * @return
     * @throws Exception
     */
    public List<Record> getQueryArguments(Modules module, HttpServletRequest request) throws Exception {
        List<Record> args = new ArrayList<Record>();
        List<Columns> columns = getSearchedList(module);
        for (Columns column : columns) {
            Record arg = new Record();
            arg.set("key", column.getColumnName());
            arg.set("value", request.getParameter(column.getColumnName()));
            arg.set("type", column.getColumnType());
            args.add(arg);
        }
        Record arg = new Record();
        arg.set("key", "createuser");
        arg.set("value", request.getParameter("createuser"));
        arg.set("type", "int");
        arg.set("key", "createdate");
        arg.set("value", request.getParameter("createdate"));
        arg.set("type", "date");
        args.add(arg);
        return args;
    }
    /**
     * 导出时获取查询条件
     * @param module
     * @param request
     * @return
     * @throws Exception
     */
    public List<Record> getExportQueryArguments(Modules module, HttpServletRequest request) throws Exception {
        List<Record> args = new ArrayList<Record>();
        List<Columns> columns = getSearchedList(module);
        String params = request.getParameter("params");
        if(params==null||params.equals("undefined")){
            return args;
        }
        JSONObject jsonData = JSONObject.fromObject(params);
        for (Columns column : columns) {
            Record arg = new Record();
            arg.set("key", column.getColumnName());
            arg.set("value", jsonData.getString(column.getColumnName()));
            arg.set("type", column.getColumnType());
            args.add(arg);
        }
        return args;
    }

}
